import os
import subprocess
import re
import mimetypes

from damn import FileReference, AssetReference
from damn.util import ExecutableDependencies

ExecutableDependencies(['sox'])

def GetSoxTypes():
  try:
    p = subprocess.Popen(['sox', '-h'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    s, t = p.communicate()
    if p.returncode != 0:
      print("E: GetSoxTypes failed with error code %d! "%(p.returncode), s, t)
      return []
  except OSError:
    print("E: GetSoxTypes failed!", s, t)
    return []
    
  match = re.search(r'AUDIO FILE FORMATS:(.*)PLAYLIST FORMATS', s, re.DOTALL)
  if not match:
    print("E: GetSoxTypes failed to parse output!", s, t)
    return []

  extensions = match.group(1).strip().split(' ')
  mimes = []
  for ext in extensions:
    mime = mimetypes.guess_type('file.'+ext, False)[0]
    if mime: mimes.append(mime)
  return mimes

from damn.analyzer import BaseAnalyzer
class SoundAnalyzer(BaseAnalyzer):
  #handled_types = ["video/mp4", "audio/ogg", "audio/mpeg", "audio/midi"]
  handled_types = GetSoxTypes()

  def analyze(self, anURI):
    f = FileReference(anURI)
    a = AssetReference(os.path.basename(anURI), mimetypes.guess_type(anURI, False)[0], f)
    
    try:
      p = subprocess.Popen(['sox', '--i', anURI], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
      s, t = p.communicate()
      if p.returncode != 0:
        print("E: SoundAnalyzer failed %swith error code %d! "%(anURI, p.returncode), s, t)
        return False
    except OSError:
      print("E: SoundAnalyzer failed %s!"%(anURI), s, t)
      return False
    meta = {}
    lines = s.strip().split('\n')
    for line in lines:
      line = line.split(':', 1)
      if len(line) == 1:
        line = line[0].split('=')
      line = [l.strip() for l in line]
      if line[0] in ['Input File', 'Comment']: continue
      meta['Sox-'+line[0]] = line[1]
      a.AddMetaData('Sox-'+line[0], line[1])
    
    return f
 
